package com.cloudminds.resttest.helper;

import com.cloudminds.resttest.ice.AiasIceClient;
import com.cloudminds.resttest.utils.Base64Utils;
import com.cloudminds.resttest.utils.FileUtils;
import com.cloudminds.resttest.vo.CallParams;
import org.json.JSONObject;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

public class NewAsrHelper
{
	
	private static NewAsrHelper      asrHelper;
	private        File[]            audioPaths;
	private        ArrayList<byte[]> audioList             = new ArrayList<>();
	private        int               AUDIO_PER_SECTION_LEN = 5 * 1024 * 1024;
	private static int               index                 = 0;
	private        boolean           asrEnable             = false;
	private        long              sendNumber            = 0;
	private        long              responseNumber        = 0;
	private        AiasIceClient     aiasIceClient;
	
	public NewAsrHelper(String sid, AiasIceClient aiasIceClient)
	{
		this.aiasIceClient = aiasIceClient;
		asrHelper = this;
	}
	
	//     public static AsrHelper getAsrHelper(){
	//         if (asrHelper == null){
	//             asrHelper = new AsrHelper();
	//         }
	//         return  asrHelper;
	//     }
	
	private void loadAudios(String path)
	{
		File file = new File(path + "/audios");
		System.out.println("Audio folder path:" + file.getAbsolutePath());
		//遍历audios文件夹下的音频文件
		if (file.exists())
		{
			audioPaths = file.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String name)
				{
					String s = name.toLowerCase();
					if (s.startsWith("._"))
					{
						return false;
					}
					return s.endsWith(".pcm") || s.endsWith(".avi");
				}
			});
		}
		
		audioList.clear();
		//读取音频文件
		try
		{
			for (File item : audioPaths)
			{
				byte[] audio = FileUtils.getContent(item);
				if (audio != null && audio.length > 0)
				{
					audioList.add(audio);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/*private void loadAudios(File name)
	{
		audioList.clear();
		//读取音频文件
		try
		{
			byte[] audio = FileUtils.getContent(name);
			if (audio != null && audio.length > 0)
			{
				audioList.add(audio);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}*/
	
	public JSONObject startAsr(String sid)
	{
		JSONObject json = new JSONObject();
		if (audioList.size() == 0)
		{
			String path = new File("").getAbsolutePath();
			loadAudios(path);
		}
		asrEnable = true;
		if (null!=audioList && audioList.size()>0){
			index = index<audioList.size()?index:0;
			 json = sendAudioData(sid,audioList.get(index));
			index++;
		}
		return json;
	}

	public JSONObject startAsr1(String sid, String question)
	{
		audioList.clear();
		asrEnable = true;
		JSONObject json = sendtestText(sid, question);
		return json;
	}

   /* public JSONObject startAsr(File fileName){
         loadAudios(fileName);
        asrEnable = true;
       // sendThread.start();
       JSONObject json =  sendAudioData(audioList.get(0));
        return json;
    }*/
	
	public void stopAsr()
	{
		asrEnable = false;
	}
	
	public void receivedAnswer()
	{
		responseNumber++;
	}
	
	/**
	 * cloudasr 上传audio
	 *
	 * @param audioBytes
	 */
	public JSONObject sendAudioData(String sid, final byte[] audioBytes)
	{
		JSONObject json = new JSONObject();
		try
		{
			if (null == audioBytes)
			{
				System.out.println("audio is null ,return");
				return new JSONObject();
			}
			System.out.println("Send audio size:" + audioBytes.length);
			
			String audioString = Base64Utils.encodeToString(audioBytes);
			long resLen = audioString.length() % AUDIO_PER_SECTION_LEN;
			int blockNum = (int) (audioString.length() / AUDIO_PER_SECTION_LEN) + (audioString.length() % AUDIO_PER_SECTION_LEN > 0 ? 1 : 0);
			
			long seq = System.currentTimeMillis();
			for (int i = 0; i < blockNum; i++)
			{
				json.put("type", "SpeechStream");
				json.put("seq", seq);
				json.put("sid", sid);
				
				json.put("appType", "pepper");
				json.put("tenantId", CallParams.TENANT_ID);
				json.put("serviceCode", CallParams.SERVICE_CODE);
				
				JSONObject dataJson = new JSONObject();
				dataJson.put("duration", 1000);
				dataJson.put("rate", 16000);
				dataJson.put("channel", 1);
				dataJson.put("language", "zh");
				dataJson.put("format", "PCM");
				dataJson.put("account", CallParams.USER_NAME);
				int index = (int) (i * AUDIO_PER_SECTION_LEN);
				
				if (i == blockNum - 1)
				{
					dataJson.put("flag", 2);  //段尾
					dataJson.put("speech", audioString.substring(index, audioString.length()));
				}
				else if (i == 0)
				{
					dataJson.put("flag", 0); //段首
					dataJson.put("speech", audioString.substring(index, AUDIO_PER_SECTION_LEN));
				}
				else
				{
					dataJson.put("flag", 1); //段中
					dataJson.put("speech", audioString.substring(index, index + AUDIO_PER_SECTION_LEN));
				}
				json.put("data", dataJson);
				json.put("testText", "");
				
				if (null != aiasIceClient)
				{
					String jsonString = json.toString();
					//PushClient.getInstance().push2AiAs(jsonString);
					int result = aiasIceClient.sendAudio(jsonString);
					System.out.print("发送状态：" + result);
				}
				
			}
			sendNumber++;
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return json;
	}
	
	public JSONObject sendtestText(String sid, String question)
	{
		JSONObject json = new JSONObject();
		byte[] audioBytes = new byte[0];
		try
		{
			if (null == audioBytes)
			{
				System.out.println("testText is null ,return");
				return new JSONObject();
			}
			System.out.println("Send testText size:" + audioBytes.length);
			
			String audioString = Base64Utils.encodeToString(audioBytes);
			long resLen = audioString.length() % AUDIO_PER_SECTION_LEN;
			int blockNum = (int) (audioString.length() / AUDIO_PER_SECTION_LEN) + (audioString.length() % AUDIO_PER_SECTION_LEN > 0 ? 1 : 0);
			
			long seq = System.currentTimeMillis();
			for (int i = 0; i <= blockNum; i++)
			{
				json.put("type", "SpeechStream");
				json.put("seq", seq);
				json.put("sid", sid);
				json.put("appType", "pepper");
				json.put("tenantId", CallParams.TENANT_ID);
				json.put("serviceCode", CallParams.SERVICE_CODE);
				
				JSONObject dataJson = new JSONObject();
				dataJson.put("duration", 1000);
				dataJson.put("rate", 16000);
				dataJson.put("channel", 1);
				dataJson.put("language", "zh");
				dataJson.put("format", "PCM");
				dataJson.put("account", CallParams.USER_NAME);
				int index = (int) (i * AUDIO_PER_SECTION_LEN);
				
				dataJson.put("flag", 2);  //段尾
				dataJson.put("speech", audioString.substring(index, audioString.length()));
               /* if (i == blockNum-1){
                    dataJson.put("flag",2);  //段尾
                    dataJson.put("speech",audioString.substring(index,audioString.length()));
                } else if(i==0) {
                    dataJson.put("flag",0); //段首
                    dataJson.put("speech",audioString.substring(index,AUDIO_PER_SECTION_LEN));
                } else {
                    dataJson.put("flag",1); //段中
                    dataJson.put("speech",audioString.substring(index,index+AUDIO_PER_SECTION_LEN));
                }*/
				json.put("data", dataJson);
				json.put("testText", question);
				
				if (null != aiasIceClient)
				{
					String jsonString = json.toString();
					int result = aiasIceClient.sendAudio(jsonString);
					System.out.print("发送状态：" + result);
				}
				
			}
			sendNumber++;
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return json;
	}
}
